import sys
import os
from time import time, sleep
from datetime import datetime, timedelta
import itertools

if sys.platform == 'win32':
    GREEN = 0x02 
    RED   = 0x04
    GREY  = 0x07
    STDOUT = -11
    import ctypes
    std_out_handle = ctypes.windll.kernel32.GetStdHandle(STDOUT)
    setcolor = ctypes.windll.kernel32.SetConsoleTextAttribute
    def green(): setcolor(std_out_handle, GREEN)
    def red(): setcolor(std_out_handle, RED)
    def reset(): setcolor(std_out_handle, GREY)
elif os.environ.get('TERM'):
    def green(): sys.stdout.write('\033[32m')
    def red(): sys.stdout.write('\033[31m')
    def reset(): sys.stdout.write('\033[0m')
else:
    def green(): pass
    def red(): pass
    def reset(): pass

_the_start = _prev = datetime.now()
def count(c=itertools.count(1)):
    return next(c)
def elapsed(now):
    return now - _the_start
def interval(now):
    global _prev
    try:
        return now - _prev
    finally:
        _prev = now

def OK(now):
    green()
    sys.stdout.write('[OK]')
    reset()
    sys.stdout.write(' %s. %s / %s\n' % (count(), interval(now), elapsed(now)))
def FAILED(now):
    red()
    sys.stdout.write('[FAILED]')
    reset()
    sys.stdout.write(' %s. %s / %s\n' % (count(), interval(now), elapsed(now)))

class VerbosePrinter:
    def before_run(self):
        print('\nRun:')
        self.start = time()
    def after_run(self, rc):
        elapsed = time() - self.start
        if elapsed < 0.5:
            sleep(0.5 - elapsed)
        now = datetime.now()
        if rc:
            FAILED(now)
        else:
            OK(now)
